package com.gec.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.common.BaseContext;
import com.gec.common.CustomException;
import com.gec.dto.OrderQuery;
import com.gec.dto.OrdersDto;
import com.gec.entity.*;
import com.gec.mapper.OrderMapper;
import com.gec.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author : [chenxys]
 * @version : [v1.0]
 * @createTime : [2022/7/14 18:21]
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Override
    public Page<OrdersDto> pageWithOrders(Page<Orders> ordersPage, OrderQuery orderQuery) {
        Page<OrdersDto> pageInfo = new Page<>();

        // 拼接查询条件
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 订单号
        String ordersNumber = null;
        LocalDateTime orderTime = null;
        LocalDateTime checkoutTime = null;
        if (!ObjectUtils.isEmpty(orderQuery)){
            // 订单号
            ordersNumber = orderQuery.getNumber();
            // 开始时间
            orderTime = orderQuery.getBeginTime();
            // 截止时间
            checkoutTime = orderQuery.getEndTime();
        }
        // 订单号
        ordersLambdaQueryWrapper.eq(!ObjectUtils.isEmpty(ordersNumber),Orders::getNumber,ordersNumber);
        // 时间
        ordersLambdaQueryWrapper.ge(!ObjectUtils.isEmpty(orderTime),Orders::getOrderTime,orderTime);
        ordersLambdaQueryWrapper.le(!ObjectUtils.isEmpty(checkoutTime),Orders::getCheckoutTime,checkoutTime);
        // 查询基本信息
        ordersPage = this.page(ordersPage,ordersLambdaQueryWrapper);

        // 复制
        BeanUtils.copyProperties(ordersPage,pageInfo,"records");
        List<Orders> ordersList = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList = ordersList.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            // 查询其他信息
            Long userId = ordersDto.getUserId();
            // 封装查询条件
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(!ObjectUtils.isEmpty(userId),User::getId,userId);
            // 查询结果
            User user = userService.getOne(userLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(user)){
                ordersDto.setUserName(user.getName());
            }
            Long addressBookId = ordersDto.getAddressBookId();
            // 查询地址
            LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 构造条件
            addressBookLambdaQueryWrapper.eq(!ObjectUtils.isEmpty(addressBookId),AddressBook::getId,addressBookId);
            // 查询
            AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(addressBook)){
                // 收货人
                String consignee = addressBook.getConsignee();
                ordersDto.setConsignee(consignee);
                // 手机号码
                String phone = addressBook.getPhone();
                ordersDto.setPhone(phone);
                // 地址
                StringBuffer address = new StringBuffer();
                address.append(addressBook.getProvinceName());
                address.append(addressBook.getCityName());
                address.append(addressBook.getDetail());
                ordersDto.setAddress(String.valueOf(address));
                ordersDto.setConsignee(addressBook.getConsignee());
            }
            // ordersDtoId
            Long ordersDtoId = ordersDto.getId();
            // 构造条件
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,ordersDtoId);
            // 查询
            List<OrderDetail> detailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(detailList);
            return ordersDto;
        }).collect(Collectors.toList());
        // 赋值
        pageInfo.setRecords(ordersDtoList);
        // 返回数据
        return pageInfo;
    }

    @Override
    @Transactional
    public void submit(Orders orders) {
        // 获取用户ID
        Long currentId = BaseContext.getCurrentId();
        // 查询购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构造条件
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,currentId);
        // 查询结果
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);

        if (ObjectUtils.isEmpty(shoppingCartList)){
            throw new CustomException("购物车为空,不能下单");
        }

        // 查询用户数据
        User user = userService.getById(currentId);
        // 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        // 查询地址信息
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //
        if (ObjectUtils.isEmpty(addressBook)){
            // 地址为空
            throw new CustomException("地址信息有误,不能下单");
        }

        // 设置订单信息
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);

        // 设置用户ID
        orders.setUserId(currentId);
        // 设置用户名称
        orders.setUserName(user.getName());
        // 设置收货人信息
        orders.setConsignee(addressBook.getConsignee());
        // 设置收件人电话号码
        orders.setPhone(addressBook.getPhone());
        // 设置地址
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                        (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                        (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                        (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
        orders.setAmount(new BigDecimal(0));
        // 保存订单信息
        this.save(orders);

        // 获取订单号
        Long orderId = orders.getId();

        AtomicInteger atomicInteger = new AtomicInteger(0);

        // 订单详情
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            // 设置订单ID
            orderDetail.setOrderId(orderId);
            // 设置商品数量
            orderDetail.setNumber(item.getNumber());
            // 设置菜品口味
            orderDetail.setDishFlavor(item.getDishFlavor());
            // 设置菜品ID
            orderDetail.setDishId(item.getDishId());
            // 设置套餐ID
            orderDetail.setSetmealId(item.getSetmealId());
            // 设置名称
            orderDetail.setName(item.getName());
            // 设置菜品图片
            orderDetail.setImage(item.getImage());
            // 设置amount
            orderDetail.setAmount(item.getAmount());
            // 设置总金额
            atomicInteger.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setNumber(orderId.toString());
        // 总金额
        orders.setAmount(new BigDecimal(atomicInteger.get()));
        // 保存数据
        // --> 订单表
        this.updateById(orders);
        // --> 订单明细表
        orderDetailService.saveBatch(orderDetailList);
        // 清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
    }

    @Override
    public Page<OrdersDto> getUserPage(Long page, Long pageSize) {
        // 查询基础信息
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 用户ID
        Long userId = BaseContext.getCurrentId();
        // 构造查询条件
        ordersLambdaQueryWrapper.eq(Orders::getUserId,userId);
        // 查询基本信息
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        this.page(ordersPage,ordersLambdaQueryWrapper);
        // 展示数据的分页
        Page<OrdersDto> ordersDtoPage = new Page<>();
        // 复制
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        List<Orders> ordersList = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList = ordersList.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            // 复制基本信息
            BeanUtils.copyProperties(item,ordersDto);
            // 获取用户信息
            User user = userService.getById(userId);
            // 获取地址信息
            Long addressBookId = item.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            // 获取订单详情
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 构造条件
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            // 赋值
            if (!ObjectUtils.isEmpty(user)){
                String userName = user.getName();
                ordersDto.setUserName(userName);
            }
            if (!ObjectUtils.isEmpty(addressBook)){
                String phone = addressBook.getPhone();
                StringBuffer address = new StringBuffer();
                address.append(addressBook.getProvinceName());
                address.append(addressBook.getCityName());
                address.append(addressBook.getDetail());

                ordersDto.setPhone(phone);
                ordersDto.setAddress(String.valueOf(address));
                ordersDto.setConsignee(addressBook.getConsignee());
            }
            if (!ObjectUtils.isEmpty(orderDetailList)){
                ordersDto.setOrderDetails(orderDetailList);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        // 赋值给分页
        ordersDtoPage.setRecords(ordersDtoList);
        // 返回信息
        return ordersDtoPage;
    }

    @Override
    public void updateStatus(Orders orders) {
        LambdaUpdateWrapper<Orders> ordersLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 新值
        ordersLambdaUpdateWrapper.set(Orders::getStatus,orders.getStatus());
        // 条件
        ordersLambdaUpdateWrapper.eq(Orders::getId,orders.getId());
        this.update(ordersLambdaUpdateWrapper);
    }
}
